define(['./BaseView', 'iscroll', 'backbone.paginator', './ContainerView'], function(BaseView, IScroll, PageableCollection, ContainerView) {

  var ListRow = BaseView.extend({
    type: 'ListViewRow',
    events: {
      "click": "RowClick"
    },

    _getPageView:function(){
      if(this.pageView){
        return this.pageView;
      }

      var parent= this.parent;
      while(parent&&parent.type&&parent.type.indexOf("PageView")<0){
        parent = parent.parent;
      }
      return parent;

    },
    RowClick: function(e) {
      if(!this.isInDesign){
        var target = e.target;
        var tagName = target.tagName.toUpperCase();

        if(tagName=="INPUT"||tagName=="BUTTON"){
          var pageView  =this._getPageView();
          var parentPage =pageView?pageView.type:"";
          if(parentPage.indexOf("PageView")>0){
            pageView.ListViewRowSelect({
              sender:this,
              arguments:{
                event:e,
                collection:this.parent.collection,
                collection_id:this.collection_id
              }
            });
          }
          return;
        }
        this.triggerEvent("ListViewRowClick", {
          e:e,
          id:this.model.get("_id"),
          collection_id:this.collection_id
        });
      }
    },

    tagName: "LI",

    initialize: function(options) {
      ContainerView.prototype.initialize.apply(this, arguments);
      this.pageView = null;
      this.isInDesign = false;
      this.model = options.model;
      this.component = options.component;
      this.component.parent = this;
      this.component.setModel(this.model);
      this.id = options.listview_id;
      this.options.triggers = options.triggers
      this.collection_id = options.collection_id;
      if (options.columncount == 2) {
        this.$el.css({
          "width": "50%",
          "float": "left"
        });
      }
      this.listenTo(this.model, "destroy", this.DestroyHandle);
      this.listenTo(this.model, "change", this.render);
    },
    DestroyHandle: function() {
      this.stopListening();
      this.$el.remove();
    },
    render: function() {
      this.$el.empty();
      if (this.component) {
        this.component.render();
        this.$el.append(this.designerWraperComponent(this.component).el);
        this.$el.append("<div class='yy-listrow-cover'></div>");
      }
      return this;
    },
    designerWraperComponent:function(component){
      var compositeHandler = component.compositeHandler||this._getCompositeHandler();
      component.compositeHandler =compositeHandler;
      if (component.compositeHandler) {
        this.isInDesign = true;
        component = component.compositeHandler(component)
      }
      return component;
    },
    onRemove: function() {
      this.stopListening();
      if (this.component) {
        this.component.onRemove();
      }
      this.$el.remove();
    }

  });

  return BaseView.extend({
    type: 'ListView',
    isContainer:true,
    events: {
      "click .nlistview-addmore": "loadMoreData"
    },
    tagName: "DIV",

    initialize:function(){
      // initial state FIXME this is rubbish code clean it ASAP
      this.listObj = null;
      this.nodata = null;
      this.iscrollObj = null;
      this.scrollWraper = null;
      this.Rows = [];
      this.number = 0;
      this.showDel = 0;
      //
      this.designerCanDragIn=false;
    },
    loadMoreData: function() {
      var _this = this;
      try
      {
        this.collection.getNextPage({
          success: function() {
            if (_this.collection.length < _this.pageSize) {
              _this.AddMoreButton.hide();
            }
          }
        });
      }catch(e){
        _this.AddMoreButton.hide();
      }

    },
    _getCollectionByCollectionName: function(collectionName) {
      var Collection;
      var _Collection = window.library.getCollection(collectionName);
      try {
        Collection = new _Collection();
      } catch (e) {
        alert(e);
      } finally {}
      return Collection;
    },
    configure: function(options) {

    },
    getConfig:function(handlers){
      var options = _.clone(this.options);
      if (!options.type) {
        options.type = this.type;
      }
      //console.log(this.$el.find(".component-handle-view"));
      if (this.$el.find(".component-handle-view")[0]) {
        var container_cid = this.$el.find(".component-handle-view")[0].getAttribute("data-cid");
        options.row =handlers[container_cid].component.getConfig();
      }
      return options;
    },
    _getCollection: function() {
      var result;
      var collectionOption=app.collections?app.collections[this.options.collection_name]:null;
      if(!collectionOption){
        //alert(this.options.collection_name+"数据源不存，请确认是否被删除或修改。")
        return;
      }
      result = this._getCollectionByCollectionName(collectionOption.type)
      if (result){
        collectionOption.url&&(result.url = collectionOption.url)
        result.collection_id = collectionOption.id
      }
      return result;
    },
    isInDesign:function(){
      return this._getCompositeHandler()!=null;
    },
    _render: function() {
      if(this.collection && this.collection.type == this.options.collection_name) {
        //collection没改变
        if (!this.options.paging) {
          this.pageSize = this.collection.state.pageSize = parseInt(this.options.pageSize) ? parseInt(this.options.pageSize) : 5;
          this.AddMoreButton.hide();
        }
        this.collection.fetch({
          success: function() {
            this.collection.state.totalPages == 1 && this.options.paging && this.AddMoreButton.hide();
          }.bind(this)
        });
        return;
      }
      //没有collection
      if (this.options && typeof this.options.collection_name == "string") {
        this.collection = this._getCollection();
      }
      if (this.collection) {
        this.stopListening(this.collection);
        this.listenTo(this.collection, 'add', this.AddRow);
        this.listenTo(this.collection, "reset", this.ResetMethod);
        this.listenTo(this.collection, "remove", function(model){model && model.trigger("destroy")});
        //this.listenTo(this.collection, "all", this.render);
        if(!this.options.paging){
          this.pageSize = this.collection.state.pageSize = parseInt(this.options.pageSize)?parseInt(this.options.pageSize):5;
          this.AddMoreButton.hide();
        }
        else{
          this.options.pageSize = parseInt(this.options.pageSize)?parseInt(this.options.pageSize):5;
          this.collection.state.pageSize=this.options.pageSize;
        }
        this.collection.fetch({
          success:function(){
          this.collection.state.totalPages==1&&this.options.paging&&this.AddMoreButton.hide();
          if(this.collection.length==0 && this.options.selectIndex == 4 && this.options.selectrowstyleindex == 4){
            if(this.isInDesign()){
              this.AddRow();
            }
          }
          }.bind(this)
        });
      } else {
        this.AddMoreButton.hide();
      }
    },
    _initIScroll: function() {
      this.iscrollObj = new IScroll(this.el, {
        probeType: 2,
        scrollX: false,
        scrollY: true,
        scrollbars: true,
        interactiveScrollbars: true,
        shrinkScrollbars: 'scale',
        fadeScrollbars: true
      });
      if (this.options.paging !== true) {
        return;
      }
      var myScroll,
        pullDownEl, pullDownOffset,
        pullUpEl, pullUpOffset,
        generatedCount = 0,
        _this = this;

      pullUpEl = $("<div class='pullUp'><span class='pullUpIcon'></span><span class='pullUpLabel'>上拉加载更多</span></div>");
      pullUpOffset = 40;
      this.scrollWraper.append(pullUpEl);
      this.iscrollObj.on("refresh", function() {
        if (pullUpEl[0].className.match('loading')) {
          pullUpEl[0].className = 'pullUp';
          //
          pullUpEl[0].querySelector('.pullUpLabel').innerHTML = ('上拉加载更多...');
        }
      });
      this.iscrollObj.on("scroll", function() {

        // if (this.y > 5 && !pullDownEl.className.match('flip')) {
        //   pullDownEl.className = 'flip';
        //   pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Release to refresh...';
        //   this.minScrollY = 0;
        // } else if (this.y < 5 && pullDownEl.className.match('flip')) {
        //   pullDownEl.className = '';
        //   pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Pull down to refresh...';
        //   this.minScrollY = -pullDownOffset;
        // } else
        if (this.y < (this.maxScrollY - 5) && !pullUpEl[0].className.match('flip')) {
          pullUpEl[0].className = 'pullUp flip';
          pullUpEl[0].querySelector('.pullUpLabel').innerHTML = ('松开刷新...');
          this.maxScrollY = this.maxScrollY;
        } else if (this.y > (this.maxScrollY + 5) && pullUpEl[0].className.match('flip')) {
          pullUpEl[0].className = 'pullUp';
          pullUpEl[0].querySelector('.pullUpLabel').innerHTML = ('上拉加载更多...');
          //    this.maxScrollY = pullUpOffset;
        }
      });
      this.iscrollObj.on("scrollEnd", function() {
        // if (pullDownEl.className.match('flip')) {
        //   pullDownEl.className = 'loading';
        //   pullDownEl.querySelector('.pullDownLabel').innerHTML = 'Loading...';
        //   pullDownAction(); // Execute custom function (ajax call?)
        // } else
        if (pullUpEl[0].className.match('flip')) {
          pullUpEl[0].className = 'pullUp loading';
          pullUpEl[0].querySelector('.pullUpLabel').innerHTML = ('玩命加载中...');
          _this.trigger("ListViewLoadMore");
        }
      })
    },

    AddRow: function(rowmodel) {
      var RowCfg = this.options.row;
      var RowControl = this.createComponent(RowCfg);
      if ((!this.nodata[0].hidden &&this.showDel == 1 && this.number==2) || (!this.nodata[0].hidden && RowControl.designerCanDragIn && this.number==2)) {
        RowControl.components = [];
        this.number = 0;
      }
      var Row = new ListRow({
        model: rowmodel,
        component: RowControl,
        triggers:this.options.triggers,
        columncount: this.options.columncount,
        collection_id:this.collection.collection_id,
        listview_id:this.options.id
      });
      Row.parent = this;
      this.trigger("addRow",Row);
      this.Rows.push(Row);
      this.nodata.css({
        "display": "none"
      });

      if ((!this.nodata[0].hidden && this.showDel == 1 && this.number<1) || (!this.nodata[0].hidden && RowControl.designerCanDragIn && this.number<1)) {

        var className = Row.el.className;
        Row.el.className = className +" showDel";
        this.number++;
      }
      this.listObj.append(Row.render().$el);
      var me = this;
      if (this.options.iscroll) {
        window.setTimeout(function() {
          me.iscrollObj.refresh();
        }, 0);
      }
    },
    createComponent: function(cfg) {
      var Component = window.library.findClassById(cfg.type);
      if (!Component)
        throw new Error('Component ' + cfg.type + ' Not Exists.');

      var component = new Component(cfg, this);
      //      this.addChild(component); //put in the view hierachy

      //component.render(); // call render after set parent
      component.setOptions(cfg.options || cfg);


      if (cfg.options) {
        console.warn("component config 'options' is deprecated, using {type: 'ImageView', src: 'xxx.png'} directly.");
      }

      return component;
    },

    ResetMethod: function() {
      this.listObj.empty();
      var _this = this;
      this.collection.each(function(model) {
        _this.AddRow(model);
      })
      // var me = this;
      // var models;
      // if (this.collection instanceof PageableCollection) {
      //   // for server mode, fullCollection is not valid
      //   if (this.collection.mode == 'server') {
      //     models = this.collection.models;
      //   } else {
      //     console.log(this.collection.fullCollection)
      //     models = this.collection.fullCollection.models;
      //   }
      // } else if (this.collection instanceof Array) {
      //   models = this.collection ;
      // } else {
      //   models = this.collection.models;
      // }
      // _.each(models, function(model) {
      //   me.AddRow(model);
      // });


    },
    render: function() {
      this.$el.empty();
      this.scrollWraper = $("<div></div>");
      this.nodata = $("<div class='nlistview-nodata'>未查询到相关数据</div>");
      this.scrollWraper.append(this.nodata);
      this.listObj = $("<ul></ul>");
      this.scrollWraper.append(this.listObj);
      this.AddMoreButton = $("<div class='nlistview-addmore'><button>加载更多</button></div>");
      this.scrollWraper.append(this.AddMoreButton);
      this.$el.append(this.scrollWraper);
      this.$el.addClass("yyn-listview");
      if (this.options.iscroll) {
        this._initIScroll();
      }

      this._render();
      return this;
    },
    onRemove: function() {
      this.collection && this.collection.reset();
      //alert(this.getChildren().length);
      for (var i = 0, j = this.Rows.length; i < j; i++) {
        this.Rows[i].onRemove();
      }
      this.stopListening();
      this.$el.remove();
    }

  });
});
